package com.fingard.dsp.bank.directbank.alipay01;

import java.net.URLEncoder;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IJSAPIOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqGenGetUserCodeURL;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqGenRealNameURL;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqUnifiedOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsGenGetUserCodeURL;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsGenRealNameURL;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsUnifiedOrder;
import com.fingard.text.StringHelper;

/**
 * 支付宝生活号支付
 * 
 * @author fanghh
 * @version 1.0
 */
public class ALIPAY01JSAPIOrder extends ALIPAY01Base implements IJSAPIOrder {
	@Override
	public RetAtsUnifiedOrder submitJSAPIOrder(ReqUnifiedOrder p_req) {
		return null;
	}

	@Override
	public RetAtsQueryOrder queryJSAPIPay(ReqQueryOrder p_req) {
		return null;
	}
	
	/**
	 * 获取用户授权URL
	 * 
	 * 参考文档在线地址：https://docs.alipay.com/fw/api/105942
	 * 参考接口：第一步：URL拼接与scope详解
	 */
	@Override
	public RetAtsGenGetUserCodeURL GenGetUserCodeURL(ReqGenGetUserCodeURL p_req) {
		RetAtsGenGetUserCodeURL retAts = new RetAtsGenGetUserCodeURL();
		
		try {
			logIsExist();
			ActSetItem actItem = this.getBankConfig().getActSetItem(p_req.ownAct, "getUserId");
			if (actItem == null) {
				actItem = this.getBankConfig().getActSetItem(p_req.ownAct, "unifiedorder");
			}
			if(actItem != null){
				String authUrl = bankFront.getUrl("authUrl"); // 授权URL
				WriteBankLogLn2("authUrl: " + authUrl);
				
				if(StringHelper.hasAnyChar(authUrl)) {
                    String authRedirectUri = p_req.authRedirectUri;
                    if (StringHelper.isNullOrEmpty(authRedirectUri)) {
                        authRedirectUri = bankFront.getUrl("authRedirectUri");// 支付宝授权回调地址
                    }

					if (p_req.type!=null&&!"".equals(p_req.type)) {
						if (!authRedirectUri.contains("?")) {
							authRedirectUri = authRedirectUri + "?type=" + p_req.type;
						} else if (!authRedirectUri.endsWith("&")) {
							authRedirectUri = authRedirectUri + "&type=" + p_req.type;
						}
					}
					WriteBankLogLn2("authRedirectUri: " + authRedirectUri);
					
					if(StringHelper.hasAnyChar(authRedirectUri)) {
						retAts.respCode = "0";
						retAts.respInfo = "成功";
						retAts.getUserCodeURL = authUrl + "?app_id=" + actItem.appId + "&scope=auth_base&redirect_uri=" + URLEncoder.encode(authRedirectUri, getCharset()) + "&state=" + p_req.urid;
					} else {
						retAts.respCode = "-1";
						retAts.respInfo = "未找到授权回调地址";
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = "未找到授权URL";
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息!";
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		return retAts;
	}

	/**
	 * 获取用户ID
	 * 
	 * 参考文档在线地址：https://docs.alipay.com/fw/api/105942
	 * 参考接口：第三步：使用auth_code换取接口access_token及用户userId
	 */
	@Override
	public RetAtsGenGetUserCodeURL getUserId(ReqGenGetUserCodeURL p_req) {
		RetAtsGenGetUserCodeURL retAts = new RetAtsGenGetUserCodeURL();
		
		try {
			logIsExist();
			
			ActSetItem actItem = getBankConfig().getActSetItem(p_req.ownAct, "unifiedorder");
			if(actItem != null){
				AlipayClient alipayClient = new DefaultAlipayClient(bankFront.serverURL, actItem.appId, 
						actItem.ownKeyStorePath, "json", getCharset(), actItem.oppCertFilePath, "RSA2");

				AlipaySystemOauthTokenRequest alipayRequest = new AlipaySystemOauthTokenRequest();
				
				alipayRequest.setGrantType("authorization_code");
				alipayRequest.setCode(p_req.code);
				
				WriteBankUrlLogLn(bankFront.serverURL);
				
				AlipaySystemOauthTokenResponse response = alipayClient.execute(alipayRequest);
				WriteBankLogStep3(response.getBody());
				
				retAts.respCode = "0";
				retAts.respInfo = response.getMsg();
				if (StringHelper.isNullOrEmpty(response.getCode())) {
					retAts.userId = response.getUserId();
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = StringHelper.joinNotEmpty("-", response.getSubCode(), response.getSubMsg());
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息!";
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		return retAts;
	}

	@Override
	public RetAtsGenRealNameURL genRealNameURL(ReqGenRealNameURL p_req) {
		// TODO Auto-generated method stub
		return null;
	}
}
